﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Logging;
using Newtonsoft.Json;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.Plans;
using ProTrack.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LogHelper = ProTrack.Api.Helper.LogHelper;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 排班计划服务接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class PlanTeamController : Controller
    {
        public PlanTeamController(IPlanTeamServices services, LogHelper LogHelper)
        {
            Services = services;
            this.LogHelper = LogHelper;
        }
        private IPlanTeamServices Services { get; }
        private LogHelper LogHelper { get; }

        /// <summary>
        /// 获取所有排班
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                return await Error("排班计划-获取所有", ex);
            }
            return Ok(status);
        }

        /// <summary>
        /// 根据页码，页大小，班组分类，排班编号，排班名称获取排班信息方法
        /// </summary>
        /// <param name="PageIndex">页码</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="TeamType">班组分类</param>
        /// <param name="PlanCode">排班编号</param>
        /// <param name="PlanName">排班名称</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string TeamType, [FromQuery] string PlanCode, [FromQuery] string PlanName)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAsync(PageIndex, PageSize, TeamType ?? "", PlanCode ?? "", PlanName ?? "");
                status.Data = list;
                status.Count = await Services.GetCountAsync(TeamType, PlanCode, PlanName);
            }
            catch (Exception ex)
            {
                return await Error("排班计划-分页获取", ex);
            }
            return Ok(status);
        }

        /// <summary>
        /// 根据排班计划编号获取排班计划人员表(排班计划附加表)方法
        /// </summary>
        /// <param name="PlanTeamId"></param>
        /// <returns></returns>
        [HttpGet("GetPlanTeambyId")]
        public async Task<IActionResult> GetPlanTeambyId([FromQuery] string PlanTeamId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetPlanTeambyIdAsync(PlanTeamId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                return await Error("排班计划-获取排班计划人员表(排班计划附加表)", ex);
            }
            return Ok(status);
        }

        /// <summary>
        /// 新增排班计划
        /// </summary>
        /// <param name="model">排班计划模型</param>
        /// <param name="PersonString">排班计划人员表(排班计划附加表)模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] PlanTeam model, [FromForm] string PersonString)
        {
            var status = BaseStatus.CreateInstance();
            List<PlanTeamItem> list = new List<PlanTeamItem>();
            try
            {
                if (!string.IsNullOrEmpty(PersonString))
                {
                    list = JsonConvert.DeserializeObject<List<PlanTeamItem>>(PersonString);
                    list.ForEach(x =>
                    {
                        x.Creator = User.Identity.Name;
                    });
                }
                model.Creator = HttpContext.User.Identity.Name;

                var isSuccess = await Services.AddAsync(model, list);
                if (isSuccess)
                    status.Msg = "新增成功";
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                return await Error("排班计划-新增", ex);
            }
            return Ok(status);
        }

        /// <summary>
        /// 修改排班计划
        /// </summary>
        /// <param name="model">排班计划模型</param>
        /// <param name="PersonString">排班计划人员表(排班计划附加表)模型</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] PlanTeam model, [FromForm] string PersonString)
        {
            var status = BaseStatus.CreateInstance();
            List<PlanTeamItem> list = new List<PlanTeamItem>();
            try
            {
                if (!string.IsNullOrEmpty(PersonString))
                {
                    list = JsonConvert.DeserializeObject<List<PlanTeamItem>>(PersonString);
                    list.ForEach(x =>
                    {
                        x.CreateTime = StringHelper.GetTimeNow();
                        x.Creator = User.Identity.Name;
                        x.PlanTeamId = model.Id;
                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = HttpContext.User.Identity.Name;
                var isSuccess = await Services.UpdateAsync(model, list);
                if (isSuccess)
                    status.Msg = "修改成功";
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                return await Error("排班计划-修改", ex);
            }
            return Ok(status);
        }

        /// <summary>
        /// 根据编号批量删除排班信息方法
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                    status.Msg = "删除成功";
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                return await Error("排班计划-批量删除", ex);
            }
            return Ok(status);
        }

        /// <summary>
        /// 删除排班计划
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteAsync(Id);
                if (isSuccess)
                    status.Msg = "删除成功";
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                return await Error("排班计划-删除", ex);
            }
            return Ok(status);
        }

        /// <summary>
        /// 错误信息
        /// </summary>
        /// <param name="ExString"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        private async Task<IActionResult> Error(string ExString, Exception ex)
        {
            var status = BaseStatus.CreateInstance();
            status.Code = -1;
            status.Msg = "服务器异常，请稍后重试";
            //写日志
            await LogHelper.WriteErrorLog(ExString, ex, HttpContext);
            return new ObjectResult(status) { StatusCode = StatusCodes.Status500InternalServerError };
        }
    }
}
